package cn.tedu._05mvcboot02.controller;

import cn.tedu._05mvcboot02.common.response.JsonResult;
import cn.tedu._05mvcboot02.common.response.StatusCode;
import cn.tedu._05mvcboot02.mapper.UserMapper;
import cn.tedu._05mvcboot02.pojo.dto.InsertDTO;
import cn.tedu._05mvcboot02.pojo.entity.User;
import cn.tedu._05mvcboot02.pojo.vo.UserListVO;
import cn.tedu._05mvcboot02.pojo.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@Api(tags = "01.用户模板")
@Slf4j
@RestController
@RequestMapping("/v1/users/")
public class UserController {

    @Autowired(required = false)
    //required=false表示装配不成功也不会报错，一般不用！
    private UserMapper userMapper;

    @ApiOperation(value = "添加用户功能")
    @PostMapping("insert")
    public JsonResult insert(InsertDTO insertDTO){

        log.debug("insertDTO = " + insertDTO);

        UserVO userVO = userMapper.SelectByUsername(insertDTO.getUsername());

        if(userVO != null){
            return new JsonResult(StatusCode.OPERATION_FAILED);
        }

        User user = new User();
        BeanUtils.copyProperties(insertDTO,user);
        user.setCreated(new Date());

        log.debug("User = "+ user);
        userMapper.insert(user);

        return JsonResult.ok();
    }

    @ApiOperation(value = "展示用户列表")
    @GetMapping("userList")
    public JsonResult userList(){
        List<UserListVO> userListVOS = userMapper.userList();
        return JsonResult.ok(userListVOS);
    }

    @ApiOperation(value = "删除指定用户功能")
    @GetMapping("delete")
    @ApiImplicitParam(name = "id" , value = "用户ID",required = true,dataType = "int")
    public JsonResult delete(Integer id){
        log.debug("id = " + id);
        userMapper.delete(id);
        return JsonResult.ok();
    }

    @ApiOperation(value = "修改用户资料")
    @PostMapping("update")
    public JsonResult update(User user){

        log.debug("user = " + user);
        userMapper.update(user);
        return JsonResult.ok();
    }

    @ApiOperation(value = "查找用户资料")
    @GetMapping("select/{id}")
    @ApiImplicitParam(name = "id", value = "用户ID",required = true,dataType = "integer",example = "200")
    public JsonResult select(@PathVariable Integer id){
        log.debug("id = " + id);

        if(id < 0){
            throw new IllegalArgumentException ("id不能小于0");
        }
        UserVO userVO = userMapper.select(id);
        return JsonResult.ok(userVO);
    }
}
